package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Exercise;
import com.itheima.pojo.Repository;
import com.itheima.service.RepositoryService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/repository")
public class RepositoryController {
    @Reference
    private RepositoryService repositoryService;
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile multipartFiles){


        try {
            if(multipartFiles.getOriginalFilename().equals("病因知识库.xls")){
                List<String[]> repos = POIUtils.readExcel(multipartFiles);
                List<Repository> repositories = new ArrayList<>();
                for (String[] repo : repos) {
                    System.out.println(repo.length);
                    Repository repository = new Repository(null,repo[1],repo[2],Integer.parseInt(repo[3]),repo[4],Integer.parseInt(repo[5]),repo[6],Integer.parseInt(repo[7]));
                    repositories.add(repository);
                }
                //将poi的数据导出到数据库
                repositoryService.add(repositories);
                //回显数据
                List<Repository>  repositories1 =  repositoryService.find();
                return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS,repositories1);
            }else{
                System.out.println(multipartFiles.getOriginalFilename());
                List<String[]> repos = POIUtils.readExcel(multipartFiles);
                List<Exercise> exercises = new ArrayList<>();
                int i=0;
                for (String[] repo : repos) {
                    if(i==0){
                        i++;
                        continue;
                    }
                    i++;
                    if(i==60){
                        break;
                    }
                    System.out.println(i);
                    System.out.println(repo.length);
                    Exercise exercise = new Exercise(null,repo[2],repo[5],repo[6],repo[10]);
                    exercises.add(exercise);
                }
                repositoryService.addExercise(exercises);
            }
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }

    }

}
